<template>
	<view class="homeLayout pageBg">
		<custom-nav-bar title="温室"></custom-nav-bar>

		<view class="banner">
			<swiper circular indicator-dots indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#fff"
				autoplay>
				<swiper-item class="first">
					<view class="left">
						<view class="row">
							<text class="label">在线设备：</text>
							<text class="value">{{Greenhouse.onlineDevicesCount}}</text>
						</view>
						<view class="row">
							<text class="label">离线设备：</text>
							<text class="value">{{Greenhouse.offlineDeveicesCount}}</text>
						</view>
						<view class="row">
							<text class="label">监测指标：</text>
							<text class="value">
								<text class="normal">{{Greenhouse.normalMetricCount}}</text>
								<text class="divider">/</text>
								<text class="abnormal">{{Greenhouse.abnormalMetricCount}}</text>
							</text>
						</view>
					</view>
					<view class="right">
						<text :class="statusClass">{{ statusText }}</text>
					</view>
				</swiper-item>
				<swiper-item class="second">
					<view class="left">
						<view class="row">
							<text class="label">产量统计</text>
							<text class="value">{{outputStatistics.year}}</text>
						</view>
						<view class="row">
							<text class="weight-value">{{outputStatistics.total}} kg</text>
						</view>
					</view>
					<view class="right">
						<view class="row">
							<text class="label">农事提醒</text>
						</view>
						<view class="row">
							<text class="label">今日待办：</text>
							<text class="value">20</text>
						</view>
						<view class="row">
							<text class="label">已完成：</text>
							<text class="value">12</text>
						</view>
					</view>
				</swiper-item>
				<swiper-item class="third">
					<view class="tempTitle">
						<text>实时温度</text>
					</view>
					<view class="tempRow">
						<text class="tempItem">36.5度</text>
						<text class="tempItem">38.1度</text>
						<text class="tempItem">35.9度</text>
						<text class="tempItem">35.2度</text>
						<text class="tempItem">35.2度</text>
						<text class="tempItem">35.2度</text>
						<text class="tempItem">35.2度</text>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<view class="functionMenu">
			<navigator class="menuItem" url="/pages/index/dataAnalysis/dataAnalysis">
				<view class="box">
					<image src="/static/images/functionMenu/visualMonitoring.png" mode="aspectFill"></image>
					<view>数据分析</view>
				</view>
			</navigator>
			<navigator class="menuItem" url="/pages/index/videoSurveillance/videoSurveillance">
				<view class="box">
					<image src="/static/images/functionMenu/videoMonitoring.png" mode="aspectFill"></image>
					<view>视频监控</view>
				</view>
			</navigator>
			<navigator class="menuItem" url="/pages/index/alarmNotification/alarmNotification">
				<!-- 				<view class="box">
					<image src="/static/images/functionMenu/alarm.png" mode="aspectFill"></image>
					<view>告警通知</view>
				</view> -->
				<uni-badge class="uni-badge-left-margin" :text="value" absolute="rightTop" size="small">
					<view class="box">
						<image src="/static/images/functionMenu/alarm.png" mode="aspectFill"></image>
						<view>告警通知</view>
					</view>
				</uni-badge>
				<!-- <uni-badge class="box" :text="8" absolute="rightTop" :offset="[-3, -3]" size="small"> -->
<!-- 				<uni-badge class="box" :text="value" absolute="rightTop" size="small">
					<image src="/static/images/functionMenu/alarm.png" mode="aspectFill"></image>
					<view>告警通知</view>
				</uni-badge> -->
			</navigator>
			<navigator class="menuItem" url="/pages/index/healthCheck/healthCheck">
				<view class="box">
					<image src="/static/images/functionMenu/history.png" mode="aspectFill"></image>
					<view>健康检查</view>
				</view>
			</navigator>
		</view>

		<!-- 数据分析 -->
		<view class="lineGraph" v-if="showLineGraphStatus">
			<HorizontalTabs :items="items" v-model="current">
			</HorizontalTabs>
			<view class="graph-content">
				<view>
					<l-echart ref="chartRef" @finished="initChart"></l-echart>
				</view>
			</view>
		</view>

		<!-- 视频监控 -->
		<view class="monitorHistory" v-if="showMonitorStatus">
			<uni-card style="padding: 0;">
				<view class="monitor-top">
					<uni-section title="监控历史" type="line"></uni-section>
					<uni-icons type="videocam-filled" size="20"></uni-icons>
				</view>
				<view class="monitor-image">
					<HorizontalTabs :items="monitoritems" v-model="monitorcurrent" />
					<view class="image-list">
						<swiper class="image-swiper" circular indicator-dots indicator-color="rgba(255,255,255,0.5)"
							indicator-active-color="#fff" autoplay>
							<swiper-item v-for="(item, index) in deviceImages" :key="index">
								<image class="full-image" :src="baseUrl + item.path" mode="aspectFill" />
								<text>{{ item.pointName }}</text>
							</swiper-item>
						</swiper>
					</view>
				</view>

			</uni-card>
		</view>


	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		onMounted,
		computed
	} from 'vue';
	import HorizontalTabs from '@/components/horizontal-tabs-bar/horizontal-tabs-bar.vue';
	import { getHouseId } from '@/utils/house.js'
	// 仅在小程序环境下引入 ECharts
	// #ifdef MP
	const echarts = require('../../static/echarts.min.js')
	// #endif
	// #ifndef MP
	//const echarts = null // H5 和 App 环境不需要手动引入
	import * as echarts from 'echarts'
	// #endif

	const baseUrl = 'http://ivegetable.jaas.ac.cn/'
	const showLineGraphStatus = ref(true);
	const showMonitorStatus = ref(false);

	const items = ref([]);
	const current = ref(0);
	const chartRef = ref(null);
	const chartData = ref({});
	let chartInstance = null;
	let chartInitialized = false;
	const monitoritems = ref([]);
	const monitorcurrent = ref(0);
	const deviceImages = ref([]);
	// 产量统计
	const outputStatistics = ref({});
	// 温室检测对象
	const Greenhouse = ref({});
	// 实时温度
	const RealTemperature = ref({});
	const value = ref(9);

	const getEnvTab = async (index) => {
		items.value = [{
				label: '温度',
				id: 0
			},
			{
				label: '湿度',
				id: 1
			},
			{
				label: '光照辐射&辐射',
				id: 2
			},
			{
				label: '土壤&EC',
				id: 3
			}
		]
	}

	// 获取图表数据（根据 tab 索引）
	const fetchChartData = async (index) => {
		try {
			const now = new Date()

			// 格式化为 "YYYY-MM-DD"
			const pad = (n) => n.toString().padStart(2, '0')
			const year = now.getFullYear()
			const month = pad(now.getMonth() + 1)
			const day = pad(now.getDate())

			const startTime = `${year}-${month}-${day}`
			const endTime = `${year}-${month}-${day}`

			// 格式化为 "YYYYMMDDHHmm"
			const start = Number(`${year}${month}${day}0000`)
			const end = Number(`${year}${month}${day}2359`)

			const res = await uni.request({
				url: 'http://localhost:28756/app/health/getFusionData',
				method: 'GET',
				data: {
					houseId: getHouseId(),
					type: index + 1,
					queryType: "Minutely",
					startTime: startTime,
					endTime: endTime,
					start: start,
					end: end,
				}
			})
			chartData.value = res.data.data;
			updateChart();
			showLineGraphStatus.value = true;
		} catch (err) {
			console.error('图表数据获取失败:', err)
		}
	}

	// 构造图表配置并更新
	const updateChart = async () => {
		if (!chartRef.value) return
		// const chart = await chartRef.value.getChart?.() || await chartRef.value.init(echarts)
		const option = {
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: Array.isArray(chartData.value?.timeData) ? chartData.value.timeData : []
			},
			yAxis: {
				type: 'value'
			},
			grid: {
				left: 0,
				top: 10,
				bottom: 0,
				containLabel: false
			},
			series: Array.isArray(chartData.value?.series) ?
				chartData.value.series
				.filter(s => Array.isArray(s.data)) // 过滤掉无效数据项
				.map(s => ({
					name: s.name || '未命名',
					type: 'line',
					data: s.data.map(v => {
						const num = parseFloat(v)
						return isNaN(num) ? null : num // 防止 NaN 渲染异常
					}),
					smooth: true,
					stack: 'Total'
				})) : []

		}

		chartInstance.setOption(option)
	}

	// 监听 tab 切换
	watch(current, (newIndex) => {
		fetchChartData(newIndex)
	})
	// 监听视频监控tab切换
	watch(monitorcurrent, (newIndex) => {
		const selected = monitoritems.value[newIndex]
		if (selected) {
			getfetchVideoStream(selected.id);
		}
	})

	// 首次加载
	onMounted(() => {
		fetchChartData(current.value)
		getEnvTab();
		getImagesTab();
		getCropOutPutSum();
		getGreenhouseInfo();
		getHouseTemperature();
	})

	// 初始化图表
	const initChart = async () => {
		if (!chartRef.value) return

		try {
			chartInstance = await chartRef.value.init(echarts);
			// chart.setOption(option)
			// fetchChartData(current.value) // 触发数据请求和 setOption
		} catch (error) {
			console.error('图表初始化失败:', error)
		}
	}

	const getImagesTab = async () => {
		try {
			const res = await uni.request({
				url: 'http://localhost:28756/app/home/findVideoList',
				method: 'GET',
				data: {
					houseId: getHouseId()
				}
			})
			monitoritems.value = res.data.data.map(item => ({
				label: item.pointName,
				id: item.deviceId
			}));

			const firstDeviceId = monitoritems.value[0]?.id
			if (firstDeviceId) {
				getfetchVideoStream(firstDeviceId)
			}
			showMonitorStatus.value = true;
		} catch (err) {
			console.error('监控点位数据获取失败:', err)
		}
	}

	const getfetchVideoStream = async (deviceId) => {
		const res = await uni.request({
			url: 'http://localhost:28756/app/health/getVideoScreen',
			method: 'GET',
			data: {
				deviceId: deviceId,
				page: 1,
				limit: 10
			}
		})
		deviceImages.value = res.data.data.screenShotList;
	}
	
	const getCropOutPutSum = async () => {
		const res = await uni.request({
			url: 'http://localhost:28756/app/health/cropOutPutSum',
			method: 'GET',
			data: {
				houseId: getHouseId()
			}
		})
		outputStatistics.value = res.data.data;
	}
	
	const getGreenhouseInfo = async () => {
		const res = await uni.request({
			url: 'http://localhost:28756/app/health/getGreenhouseInfo',
			method: 'GET',
			data: {
				houseId: getHouseId()
			}
		})
		Greenhouse.value = res.data.data;
	}
	
	// 状态文字映射
	const statusText = computed(() => {
	  if (Greenhouse.value.checkStatus === 0) return '正常'
	  if (Greenhouse.value.checkStatus === 1) return '异常'
	  if (Greenhouse.value.checkStatus === 2) return '等'
	  if (Greenhouse.value.checkStatus === 3) return '等'
	  if (Greenhouse.value.checkStatus === 4) return '等'
	  return ''
	})
	
	// 状态样式映射
	const statusClass = computed(() => {
	  if (Greenhouse.value.status === 0) return 'normal'
	  if (Greenhouse.value.status === 1) return 'error'
	  if (Greenhouse.value.status === 2) return 'waiting'
	  if (Greenhouse.value.status === 3) return 'waiting'
	  if (Greenhouse.value.status === 4) return 'waiting'
	  return ''
	})
	
	const getHouseTemperature = async () => {
		const res = await uni.request({
			url: 'http://localhost:28756/app/sensor/getHouseTemperature',
			method: 'GET',
			data: {
				houseId: getHouseId()
			}
		})
		RealTemperature.value = res.data.data;
	}

	function onClickItem(e) {
		if (current != e.currentIndex) {
			current.value = e.currentIndex;
		}
	}
</script>

<style lang="scss" scoped>
	.homeLayout {
		.banner {
			// width: 750rpx;
			// padding: 30rpx 0;
			margin: 30rpx 30rpx;
			border-radius: 10rpx;
			background-color: #ffffff;
			box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
			height: 220rpx;

			swiper {
				// width: 750rpx;

				// padding: 24rpx;
				width: 100%;
				height: 100%;

				swiper-item {
					width: 100%;
					height: 100%;
					display: flex;

					&.first {
						display: flex;
						flex-direction: row;

						.left {
							flex: 5;
							display: flex;
							flex-direction: column;
							justify-content: center;
							padding: 0 20rpx;

							.row {
								display: flex;
								flex-direction: row;
								align-items: center;
								justify-content: space-between; // 左右对齐
								margin-bottom: 12rpx;

								.label {
									// font-weight: bold;
									// color: #333;
								}

								.value {
									color: #007aff;
									text-align: right; // 保证文字靠右

									.abnormal {
										color: #ff3b30;
									}

									.divider {
										color: #000000;
									}
								}

							}

						}

						.right {
							flex: 2;
							background-color: #d0ffd0;
							display: flex;
							justify-content: center;
							align-items: center;
						}
					}

					&.second {
						display: flex;
						flex-direction: row;

						.left {
							flex: 1; // 左边占一半
							display: flex;
							flex-direction: column; // 内部纵向排列
							justify-content: center;
							border-right: 2rpx solid #e0e0e0; // 左右之间的分割线

							.row {
								display: flex;
								flex-direction: row; // 每行横向排列 label + value
								justify-content: space-between;
								align-items: center;
								margin-bottom: 12rpx;
								padding: 0 20rpx;

								.label {
									// font-weight: bold;
									margin-right: 10rpx;
								}

								.value {
									color: #007aff;
								}

								.weight-value {
									flex: 1;
									display: flex;
									justify-content: center;
									align-items: center;
									color: #007aff;
								}
							}
						}

						.right {
							flex: 1; // 右边占一半
							display: flex;
							flex-direction: column; // 内部纵向排列
							justify-content: center;

							.row {
								display: flex;
								flex-direction: row;
								justify-content: space-between;
								align-items: center;
								padding: 0 20rpx;
								margin-bottom: 12rpx;

								.label {
									// font-weight: bold;
									margin-right: 10rpx;
								}

								.value {
									color: #007aff;
								}
							}
						}
					}

					&.third {
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;

						.tempTitle {
							margin-bottom: 12rpx;

							text {
								// font-size: 28rpx;
								// font-weight: bold;
								// color: #333;
							}
						}

						.tempRow {
							display: flex;
							flex-wrap: wrap; // 自动换行，数量不固定时也能排版
							justify-content: space-around; // 平均分布
							width: 100%;

							.tempItem {
								flex: 1; // 每个温度值等宽
								min-width: 120rpx; // 保证最小宽度，避免太挤
								text-align: center;
								// font-size: 24rpx;
								color: #007aff;
								margin-bottom: 12rpx; // 多行时行间距
							}
						}
					}


				}
			}
		}

		.functionMenu {
			// width: 690rpx;
			height: 200rpx;
			// background: $text-font-color-4;
			margin: 30rpx auto;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;

			.menuItem {
				width: 750rpx; // 四个等宽分布，留出间距
				display: flex;
				flex-direction: column;
				align-items: center;
				text-align: center;

				image {
					width: 90rpx;
					height: 90rpx;
					margin-bottom: 10rpx;
				}

				text {
					font-size: 28rpx;
					color: $text-font-color-5;
				}
			}
		}

		.lineGraph {
			width: 720rpx;
			margin-left: 30rpx;
			margin-top: 30rpx;

			/* 最后一个额外右边距 */
			.tab-item:last-child {
				margin-right: 30rpx;
			}

			.graph-content {
				border-bottom-left-radius: 10rpx;
				border-bottom-right-radius: 10rpx;
				background-color: #ffffff;
				box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
				margin-right: 30rpx;

				view {
					width: 750rpx;
					height: 550rpx;
				}
			}
		}

		.monitorHistory {
			height: 570rpx;
			margin-bottom: 30rpx;

			::v-deep .uni-section .uni-section-header {
				padding: 0 !important;
			}

			.uni-card {
				height: 100%;

				.monitor-top {
					margin-bottom: 10rpx;
					display: flex;
					justify-content: space-between; // 左右分布
					align-items: center; // 垂直居中
				}

				.monitor-image {
					background: #ddd;
					width: 100%;
					height: 100%;
					overflow: hidden;
					position: relative;

					.image-swiper {
						height: 400rpx;
					}

					.full-image {
						width: 100%;
						height: 100%;
						object-fit: cover; //兼容性增强（微信小程序不支持，但 App/H5 支持）
					}
				}
			}

		}
	}
</style>